<template>
  <div class="app-container">
    <div class="contentBox">
      <div class="searchBox">
        <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
          <el-form-item prop="warehouseId" style="margin: 0 6px 0 0;">
            <div class="searchValueBox pageFlex pageAlignCenter" @click="showTableModal('warehouseId', 'search')">
              <el-text class="value">{{ queryParams.warehouseId || '请选择仓库' }}</el-text>
              <el-icon><ArrowRight /></el-icon>
            </div>
          </el-form-item>
          <el-form-item prop="shelfId" style="margin: 0 6px 0 0;">
            <div class="searchValueBox pageFlex pageAlignCenter" @click="showTableModal('shelfId', 'search')">
              <el-text class="value">{{ queryParams.shelfId || '请选择货架' }}</el-text>
              <el-icon><ArrowRight /></el-icon>
            </div>
          </el-form-item>
          <el-form-item prop="name" style="margin: 0 6px 0 0;">
            <el-input
                class="inputBox"
                v-model="queryParams.name"
                placeholder="请输入货位名称搜索"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item style="margin: 0 6px 0 0;">
            <el-button class="normalFormBg searchBtn" icon="Search" @click="handleQuery"></el-button>
            <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetQuery"></el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-row :gutter="10" style="margin: 16px 0;">
        <el-col :span="1.5">
          <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:locationManage:add']"
               @click="handleAdd()">
            <img src="@/assets/images/plus.png" class="normalBtn_icon">
            <div class="normalBtn_text">新增</div>
          </div>
        </el-col>
      </el-row>
      <el-table
          v-loading="loading"
          :data="dataList"
          border>
        <el-table-column prop="id" label="货位ID" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
        <el-table-column prop="locationNo" label="货位编码" width="200" :show-overflow-tooltip="true" fixed="left"></el-table-column>
        <el-table-column prop="name" label="货位名称" width="200" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="cover" label="货位图片" width="80" align="center">
          <template #default="scope">
            <div class="tableImgBox1">
              <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)"
                        @click="handlePreviewShow(setCoverUrl(scope.row.cover))" v-if="scope.row.cover" />
              <div class="emptyBox" v-else>暂无图片</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="存储数量" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="type" label="类别" width="150" :show-overflow-tooltip="true">
          <template #default="scope">
            <div v-for="(item, index) in gas_stock_warehouse_type" :key="index" v-show="item.value == scope.row.type">
              <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
              <div v-else>{{ item.label }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="intro" label="介绍" width="400" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="isEnable" label="状态" width="70">
          <template #default="scope">
            <div v-for="(item, index) in system_open_status" :key="index" v-show="item.value == scope.row.isEnable">
              <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
              <div v-else>{{ item.label }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" align="center" fixed="right">
          <template #default="scope">
            <div class="pageFlex pageFlexCenter" style="width: 100%;">
              <div class="pageFlex pageFlexCenter btnSetBox" @click="handleInfo(scope.row.id)">
                <img src="@/assets/images/fileManage.png" class="img">
                <div class="text">详情</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:locationManage:goodsInfo']"
                   @click="toPage('/gasManage/stockManage/locationManage/ware-house/printLocation/'+scope.row.id)">
                <img src="@/assets/images/fileManage.png" class="img">
                <div class="text">货位卡</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:locationManage:edit']"
                   @click="handleEdit(scope.row.id)">
                <img src="@/assets/images/edit.png" class="img">
                <div class="text">修改</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:locationManage:delete']"
                   @click="handleDelete(scope.row.id, scope.row.name)">
                <img src="@/assets/images/delete.png" class="img">
                <div class="text">删除</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据"/>
        </template>
      </el-table>
      <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
        <div class="totalText">共计 {{total}} 条</div>
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="queryParams.page" :page-size="queryParams.pageSize" @current-change="handleCurrentChange"/>
      </div>
    </div>
    <el-image-viewer :url-list="srcList" @close="handlePreviewClose" v-if="showPreview"/>
    <el-drawer v-model="modalShow" direction="rtl" size="650" :title="modalTitle">
      <div class="modalBox">
        <div class="modalBoxContent">
          <el-form
              ref="formRef"
              class="formContent"
              label-width="120"
              :model="form"
              :rules="rules"
              :disabled="modalTitle === '货位详情'"
          >
            <div class="formContentTop pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">货位信息</div>
            </div>
            <div class="formContentCenter bgFF">
              <el-form-item label="所属仓库" prop="warehouseId">
                <div class="valueBox pageFlex pageAlignCenter" :class="{'disable': modalTitle === '货位详情'}" @click="showTableModal('warehouseId')">
                  <el-text class="value">{{ form.warehouseId || '请选择所属仓库' }}</el-text>
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </el-form-item>
              <el-form-item label="所属货架" prop="shelfId">
                <div class="valueBox pageFlex pageAlignCenter" :class="{'disable': modalTitle === '货架详情'}" @click="showTableModal('shelfId')">
                  <el-text class="value">{{ form.shelfId || '请选择所属货架' }}</el-text>
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </el-form-item>
              <el-form-item label="货位图片" prop="cover">
                <div class="imgBox">
                  <ImageUpload ref="cover" v-model="form.cover" bg="#FFFFFF" v-if="modalShow"></ImageUpload>
                </div>
              </el-form-item>
              <el-form-item label="货位名称" prop="name">
                <el-input
                    class="inputBox"
                    v-model="form.name"
                    placeholder="请输入货位名称"
                    clearable
                />
              </el-form-item>
              <el-form-item label="货位存储类型" prop="type">
                <el-select class="inputBox" v-model="form.type" placeholder="请选择存储类型" clearable>
                  <el-option v-for="dict in gas_stock_warehouse_type" :key="dict.value" :label="dict.label"
                             :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="存储数量" prop="quantity">
                <el-input
                    class="inputBox"
                    type="number"
                    v-model="form.quantity"
                    placeholder="请输入存储数量"
                    clearable
                />
              </el-form-item>
              <el-form-item label="存储条件" prop="storageCondition">
                <el-input
                    class="textareaBox"
                    type="textarea"
                    v-model="form.storageCondition"
                    :rows="6"
                    placeholder="请输入存储条件"
                />
              </el-form-item>
              <el-form-item label="货位介绍" prop="intro">
                <el-input
                    class="textareaBox"
                    type="textarea"
                    v-model="form.intro"
                    :rows="6"
                    placeholder="请输入货位介绍"
                />
              </el-form-item>
              <el-form-item label="备注说明" prop="remarks">
                <el-input
                    class="textareaBox"
                    type="textarea"
                    v-model="form.remarks"
                    :rows="6"
                    placeholder="请输入备注说明"
                />
              </el-form-item>
              <el-form-item label="状态" prop="isEnable">
                <el-radio-group v-model="form.isEnable">
                  <el-radio
                      v-for="dict in system_open_status"
                      :key="dict.value"
                      :value="dict.value"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="lineBox" v-if="modalTitle !== '货位详情'"></div>
        <div class="bottomBox pageFlex pageFlexCenter" v-if="modalTitle !== '货位详情'">
          <el-button type="primary" :loading="submitLoading" @click="submitNow">确认提交</el-button>
        </div>
        <el-button type="primary" :loading="formLoading" class="modalLoadingBox" v-if="formLoading">加载数据中</el-button>
      </div>
    </el-drawer>
    <el-dialog v-model="warehouseShow" :title="warehouseTitle" width="900">
      <div class="tableModalBox" v-if="warehouseShow">
        <div class="tableModalBox_top pageFlex pageAlignCenter">
          <div class="line"></div>
          <div class="title">请进行选择</div>
        </div>
        <div class="searchBox">
          <el-form :model="warehouseParams" ref="warehouseTableModal" :inline="true" @submit.prevent>
            <el-form-item prop="name" style="margin: 0 6px 0 0;">
              <el-input
                  class="inputBox"
                  v-model="warehouseParams.name"
                  placeholder="请输入仓库名查询"
                  clearable
                  @keyup.enter="handleTableModalQuery()"
              />
            </el-form-item>
            <el-form-item style="margin: 0 6px 0 0;">
              <el-button class="normalFormBg searchBtn" icon="Search" @click="handleTableModalQuery()"></el-button>
              <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetTableModalQuery()"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="tableBox">
          <el-table
            ref="warehouseTableRef"
            v-loading="warehouseLoading"
            :data="warehouseDataList"
            border
            height="400"
            @select="handleTableModalSelect"
            @select-all="handleTableModalAll">
            <el-table-column type="selection" width="55" :selectable="setTableModalSelectable"/>
            <el-table-column prop="id" label="仓库ID" width="200" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="warehouseNo" label="仓库编码" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="name" label="仓库名称" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="cover" label="仓库图片" width="80" align="center">
              <template #default="scope">
                <div class="tableImgBox1">
                  <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)"
                    @click="handlePreviewShow(setCoverUrl(scope.row.cover))" v-if="scope.row.cover" />
                  <div class="emptyBox" v-else>暂无图片</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="capacity" label="容量" width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="所属区域" width="200" :show-overflow-tooltip="true">
              <template #default="scope">
                <div>{{scope.row.province}}/{{scope.row.city}}/{{scope.row.district}}</div>
              </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" width="200" :show-overflow-tooltip="true"></el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
          <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
            <div class="totalText">共计 {{warehouseTotal}} 条</div>
            <el-pagination background layout="prev, pager, next" :total="warehouseTotal" :current-page="warehouseParams.pageNum" :page-size="warehouseParams.pageSize" @current-change="handleTablePageChange"/>
          </div>
        </div>
        <div class="lineBox"></div>
        <div class="bottomBox pageFlex pageFlexCenter">
          <el-button @click="clearTableModalChoose">清空当前选择</el-button>
          <el-button type="primary" :disabled="!warehouseCur" @click="confirmTableModalChoose">确认选择</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="shelfShow" title="选择货架" width="1000">
      <div class="tableModalBox" v-if="shelfShow">
        <div class="tableModalBox_top pageFlex pageAlignCenter">
          <div class="line"></div>
          <div class="title">请进行选择</div>
        </div>
        <div class="searchBox">
          <el-form :model="shelfParams" ref="shelfTableModal" :inline="true" @submit.prevent>
            <el-form-item prop="name" style="margin: 0 6px 0 0;">
              <el-input
                  class="inputBox"
                  v-model="shelfParams.name"
                  placeholder="请输入货架名称"
                  clearable
                  @keyup.enter="handleTableModalQuery()"
              />
            </el-form-item>
            <el-form-item style="margin: 0 6px 0 0;">
              <el-button class="normalFormBg searchBtn" icon="Search" @click="handleTableModalQuery()"></el-button>
              <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetTableModalQuery()"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="tableBox">
          <el-table
            ref="shelfTableRef"
            v-loading="shelfLoading"
            :data="shelfDataList"
            border
            height="400"
            @select="handleTableModalSelect"
            @select-all="handleTableModalAll">
            <el-table-column type="selection" width="55" :selectable="setTableModalSelectable"/>
            <el-table-column prop="id" label="货架ID" width="200" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="shelvesNo" label="货架编码" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="name" label="货架名称" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="cover" label="货架图片" width="80" align="center">
              <template #default="scope">
                <div class="tableImgBox2">
                  <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)" v-if="scope.row.cover" />
                  <div class="emptyBox" v-else>暂无图片</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="capacity" label="容量" width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="layer" label="层数" width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="position" label="位置" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="material" label="材质" width="200" :show-overflow-tooltip="true"></el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
          <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
            <div class="totalText">共计 {{shelfTotal}} 条</div>
            <el-pagination background layout="prev, pager, next" :total="shelfTotal" :current-page="shelfParams.pageNum" :page-size="shelfParams.pageSize" @current-change="handleTablePageChange"/>
          </div>
        </div>
        <div class="lineBox"></div>
        <div class="bottomBox pageFlex pageFlexCenter">
          <el-button @click="clearTableModalChoose">清空当前选择</el-button>
          <el-button type="primary" :disabled="!shelfCur" @click="confirmTableModalChoose">确认选择</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import {computed, nextTick, onMounted, watch} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { searchShelvesApi } from '@/api/gasManage/stockManage/shelfManage';
import { searchLocationApi, addLocation, getLocationById, editLocation, deleteLocation } from '@/api/gasManage/stockManage/locationManage';
import ImageUpload from '@/views/gasManage/components/ImageUpload';
import {ElLoading, ElMessageBox} from "element-plus";
const { proxy } = getCurrentInstance();
const { system_open_status, gas_stock_warehouse_type } = proxy.useDict("system_open_status", "gas_stock_warehouse_type");
const router = useRouter();
const route = useRoute();
// ------------------------------监听路由--------------------------
import useTagsViewStore from "@/store/modules/tagsView.js";
const useTagsView = useTagsViewStore();
const watchRoutes = watch(route, (val) =>{
  let str = '/gasManage/stockManage/locationManage';
  if(val.path === str){
    queryParams.value.warehouseId = route.query.warehouseId || '';
    queryParams.value.shelfId = route.query.shelfId || '';
    handleQuery();
  }else{
    let index = useTagsView.$state.visitedViews.findIndex(item=>item.path === str);
    if(index === -1){
      watchRoutes();
    }
  }
})
// -------------------------------查询-----------------------------
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  warehouseId: '',
  shelfId: '',
  name: ''
})
const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const showPreview = ref(false);
const srcList = ref([])
function handleQuery(){
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery(){
  proxy.resetForm("queryRef");
  handleQuery();
}
async function getList(){
  loading.value = true;
  let data = await getLocationData();
  if(data.length > 0){
    dataList.value = data;
  }else{
    dataList.value = [];
    total.value = 0;
  }
  loading.value = false;
}
function getLocationData(){
  return new Promise((resolve, reject) => {
    searchLocationApi(queryParams.value).then(res => {
      total.value = Number(res.total);
      resolve(Array.isArray(res.rows) ? res.rows : []);
    }).catch(()=>{
      resolve([]);
    })
  })
}
function handleCurrentChange(e){
  queryParams.value.pageNum = e;
  getList();
}
function handlePreviewShow(link){
  srcList.value = [link];
  showPreview.value = true;
}
function handlePreviewClose(){
  showPreview.value = false;
  srcList.value = [];
}
function toPage(link, row){
  let url = link;
  if(row){
    url += row.id
  }
  router.push(url);
}
// --------------------------------------表格弹窗统一处理----------------------------
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
import { searchWarehouseApi } from '@/api/gasManage/stockManage/storageManage';
function showTableModal(name, source){
  if(modalTitle.value === '货位详情') return;
  shelfShow.value = false;
  shelfSource.value = false;
  shelfCur.value = null;
  warehouseShow.value = false;
  warehouseSource.value = '';
  warehouseCur.value = null;
  if(name === 'warehouseId'){
    warehouseSource.value = source;
    warehouseShow.value = true;
    warehouseTitle.value = '选择所属仓库';
    nextTick(()=>{
      proxy.$refs.warehouseTableRef.clearSelection();
    })
  }else if(name === 'shelfId'){
    shelfSource.value = source;
    if(shelfSource.value === 'search'){
      shelfParams.value.warehouseId = queryParams.value.warehouseId;
    }else{
      if(form.value.warehouseId){
        shelfParams.value.warehouseId = form.value.warehouseId;
      }else{
        proxy.$modal.msgError('请先选择所属仓库');
        return;
      }
    }
    shelfTitle.value = '选择所属货位';
    shelfShow.value = true;
    nextTick(()=>{
      proxy.$refs.shelfTableRef.clearSelection();
    })
  }
  handleTableModalQuery();
}
function handleTableModalQuery(){
  if(warehouseShow.value){
    warehouseParams.value.pageNum = 1;
  }else if(shelfShow.value){
    shelfParams.value.pageNum = 1;
  }
  handleGetTableList();
}
function handleGetTableList(){
  if(warehouseShow.value){
    warehouseLoading.value = true;
    searchWarehouseApi(warehouseParams.value).then(res=>{
      warehouseTotal.value = Number(res.total);
      warehouseDataList.value = Array.isArray(res.rows) ? res.rows : [];
      warehouseLoading.value = false;
      if(warehouseDataList.value.length && (form.value.warehouseId ||  queryParams.value.warehouseId)){
        let id = warehouseSource.value === 'search' ? queryParams.value.warehouseId : form.value.warehouseId;
        let index = warehouseDataList.value.findIndex(item=>item.id === id);
        if(index !== -1){
          nextTick(()=>{
            warehouseCur.value = warehouseDataList.value[index];
            proxy.$refs.warehouseTableRef.toggleRowSelection(warehouseCur.value, true);
          })
        }
      }
    }).catch(()=>{
      warehouseLoading.value = false;
      warehouseDataList.value = [];
    })
  }else if(shelfShow.value){
    shelfLoading.value = true;
    searchShelvesApi(shelfParams.value).then(res=>{
      shelfTotal.value = Number(res.total);
      shelfDataList.value = Array.isArray(res.rows) ? res.rows : [];
      shelfLoading.value = false;
      if(shelfDataList.value.length && (form.value.shelfId || queryParams.value.shelfId)){
        let id = shelfSource.value === 'search' ? queryParams.value.shelfId : form.value.shelfId;
        let index = shelfDataList.value.findIndex(item=>item.id === id);
        if(index !== -1){
          nextTick(()=>{
            shelfCur.value = shelfDataList.value[index];
            proxy.$refs.shelfTableRef.toggleRowSelection(shelfCur.value, true);
          })
        }
      }
    }).catch(()=>{
      shelfLoading.value = false;
      shelfDataList.value = [];
    })
  }
}
function resetTableModalQuery(){
  if(warehouseShow.value){
    proxy.resetForm("warehouseTableModal");
  }else if(shelfShow.value){
    proxy.resetForm("shelfTableModal");
  }
  handleTableModalQuery();
}
function handleTableModalSelect(e){
  let data = e[0];
  if(warehouseShow.value){
    if(e.length > 1){
      data = e[1]
    }
    if(!data || (warehouseCur.value && warehouseCur.value.id && warehouseCur.value.id === data.id)){
      warehouseCur.value = null;
      return false;
    }
    let index = warehouseDataList.value.findIndex(item=>item.id === data.id);
    proxy.$refs.warehouseTableRef.clearSelection();
    warehouseCur.value = data;
    proxy.$refs.warehouseTableRef.toggleRowSelection(warehouseDataList.value[index], true);
  }else if(shelfShow.value){
    if(e.length > 1){
      data = e[1]
    }
    if(!data || (shelfCur.value && shelfCur.value.id && shelfCur.value.id === data.id)){
      shelfCur.value = null;
      return false;
    }
    let index = shelfDataList.value.findIndex(item=>item.id === data.id);
    proxy.$refs.shelfTableRef.clearSelection();
    shelfCur.value = data;
    proxy.$refs.shelfTableRef.toggleRowSelection(shelfDataList.value[index], true);
  }
}
function handleTableModalAll(){
  if(warehouseShow.value){
    proxy.$refs.warehouseTableRef.clearSelection();
    warehouseCur.value = null;
  }else if(shelfShow.value){
    proxy.$refs.shelfTableRef.clearSelection();
    shelfCur.value = null;
  }
}
function setTableModalSelectable(row){
  return row.isEnable != 0
}
function handleTablePageChange(e){
  if(warehouseShow.value){
    warehouseParams.value.pageNum = e;
  }else if(shelfShow.value){
    shelfParams.value.pageNum = e;
  }
  handleGetTableList();
}
function clearTableModalChoose(){
  if(warehouseShow.value){
    if(warehouseSource.value === 'search'){
      queryParams.value.warehouseId = '';
      queryParams.value.shelfId = '';
      getList();
    }else{
      form.value.warehouseId = '';
      form.value.shelfId = '';
    }
    proxy.$refs.warehouseTableRef.clearSelection();
  }else if(shelfShow.value){
    if(shelfSource.value === 'search'){
      queryParams.value.shelfId = '';
      getList();
    }else{
      form.value.shelfId = '';
    }
    proxy.$refs.shelfTableRef.clearSelection();
  }
  hideTableModal();
}
function confirmTableModalChoose(){
  if(warehouseShow.value){
    if(warehouseSource.value === 'search'){
      queryParams.value.warehouseId = warehouseCur.value.id;
      queryParams.value.shelfId = '';
      handleQuery();
    }else{
      form.value.warehouseId = warehouseCur.value.id;
      form.value.shelfId = '';
    }
  }else if(shelfShow.value){
    if(shelfSource.value === 'search'){
      queryParams.value.shelfId = shelfCur.value.id;
      handleQuery();
    }else{
      form.value.shelfId = shelfCur.value.id;
    }
  }
  hideTableModal();
}
function hideTableModal(){
  if(warehouseShow.value){
    warehouseShow.value = false;
  }else if(shelfShow.value){
    shelfShow.value = false;
  }
}
// ------------------------------------货架选择表格参数-------------------------------
const shelfShow = ref(false);
const shelfSource = ref('');
const shelfLoading = ref(false);
const shelfDataList = ref([]);
const shelfTotal = ref(0);
const shelfCur = ref(null);
const shelfTitle = ref('');
const shelfParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: ''
});
// -----------------------------------选择仓库--------------------------------------
const warehouseShow = ref(false);
const warehouseSource = ref('');
const warehouseLoading = ref(false);
const warehouseDataList = ref([]);
const warehouseTotal = ref(0);
const warehouseCur = ref(null);
const warehouseTitle = ref('');
const warehouseParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: ''
});
// ------------------------------------form弹窗--------------------------------------
const modalShow = ref(false);
const modalTitle = ref('');
const formLoading = ref(false);
const submitLoading = ref(false);
const form = ref({
  cover: '',
  name: '',
  warehouseId: '',
  shelfId: '',
  type: '',
  quantity: '0',
  storageCondition: '',
  intro: '',
  remarks: '',
  isEnable: '1'
})
const rules = ref({
  warehouseId: [{ required: true, message: "请选择所属仓库", trigger: "blur" }],
  cover: [{ required: true, message: "货位图片未上传", trigger: "blur" }],
  name: [{ required: true, message: "货位名称不能为空", trigger: "blur" }],
  shelfId: [{ required: true, message: "请选择所属货位", trigger: "blur" }],
  type: [{ required: true, message: "货位存储类型未选择", trigger: "blur" }],
  quantity: [{ required: true, message: "库存数量不能为空", trigger: "blur" }],
})
function handleModalShow(name){
  modalTitle.value = name;
  modalShow.value = true;
}
function handleModalHide(){
  modalShow.value = false;
}
async function setFormData(id){
  formLoading.value = true;
  let data = await getLocationApi(id);
  if(data){
    data.isEnable = String(data.isEnable);
    form.value = data;
  }else{
    handleModalHide();
  }
  formLoading.value = false;
}
function getLocationApi(id){
  return new Promise(resolve => {
    getLocationById(id).then(res => {
      resolve(res.data);
    }).catch(()=>{
      resolve(false);
    })
  })
}
function submitNow(){
  if(submitLoading.value) return;
  proxy.$refs["formRef"].validate(valid => {
    if(valid){
      submitLoading.value = true;
      if(modalTitle.value === '新增货位'){
        addNow();
      }else{
        editNow();
      }
    }else{
      proxy.$modal.alertWarning('有必填选项未填写，请查看！');
    }
  })
}
// -----------------------详情-----------------------
function handleInfo(id){
  handleModalShow('货位详情');
  setFormData(id);
}
// -----------------------新增-----------------------
function handleAdd(){
  proxy.resetForm('formRef');
  form.value = {
    cover: '',
    name: '',
    shelfId: '',
    type: '',
    quantity: '0',
    storageCondition: '',
    intro: '',
    remarks: '',
    isEnable: '1'
  }
  handleModalShow('新增货位')
}
function addNow(){
  let params = JSON.parse(JSON.stringify(form.value));
  params.type = Number(params.type);
  addLocation(params).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('新增货位成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// -----------------------修改-----------------------
function handleEdit(id){
  handleModalShow('修改货位信息');
  setFormData(id);
}
function editNow(){
  delete form.value.createBy;
  delete form.value.createTime;
  editLocation(form.value).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('修改货位信息成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// ----------------------------删除-------------------------------
function handleDelete(id, name){
  ElMessageBox.confirm(`确认删除货位名称为【${name}】的数据`,'提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteNow(id, name);
  }).catch(() => {})
}
async function deleteNow(id, name){
  const loading = ElLoading.service({
    lock: true,
    text: '删除中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  deleteLocation(id).then(()=>{
    loading.close();
    proxy.$modal.msgSuccess(name+'货位删除成功');
    getList();
  }).catch(()=>{
    loading.close();
  })
}
onMounted(()=>{
  queryParams.value.warehouseId = route.query.warehouseId || '';
  queryParams.value.shelfId = route.query.shelfId || '';
  getList();
})
</script>
<style lang='scss' scoped>
@import "@/assets/styles/public.scss";
:deep(.el-input){
  .el-input__wrapper{
    background-color: $formBgSet;
    box-shadow: none;
  }
}
.app-container{
  width: 100%;
  min-height: calc(100vh - 66px);
  background: #F8F8F9;
  .contentBox{
    width: 100%;
    min-height: $pageMinHeight;
    background-color: #FFFFFF;
    border-radius: 5px;
    box-sizing: border-box;
    padding: 12px;
    .searchBtn{
      width: 32px;
      height: 32px;
      font-size: 12px;
      padding: 0;
      border: none;
      margin: 0 6px 0 0px;
    }
    .btnSetBox{
      padding: 0 10px;
      box-sizing: border-box;
      border-right: 1px solid $borderColor;
      cursor: pointer;
      .text{
        height: 16px;
        line-height: 16px;
        color: var(--el-color-primary);
      }
      .img{
        width: 16px;
        height: 16px;
        margin-right: 2px;
      }
      &:last-child{
        border-right: none;
      }
    }
    .totalText{
      height: 22px;
      font-weight: 400;
      font-size: 14px;
      color: #1D2129;
      line-height: 22px;
    }
    .searchValueBox{
      min-width: 200px;
      height: 32px;
      background-color: $formBgSet;
      padding: 0 10px;
      color: var(--el-text-color-regular);
      cursor: pointer;
      border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
      .value{
        flex: 1;
      }
    }
  }
  .valueBox{
    width: 360px;
    height: 32px;
    background-color: $formBgSet;
    padding: 0 10px;
    color: var(--el-text-color-regular);
    cursor: pointer;
    .value{
      flex: 1;
    }
    &.disable{
      cursor: not-allowed;
    }
  }
}
:deep(.el-drawer){
  .el-drawer__header{
    margin: 0;
    padding-bottom: 20px;
  }
  .el-drawer__body{
    padding: 0;
  }
}
</style>
